package com.ctz.commonframe.ui.widget;

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;

public abstract class AbsFilterableAdapter<T> extends BaseAdapter implements Filterable{
	protected Context context;
	protected List<T> datas;
	protected LayoutInflater inflater;
	protected int layoutId;
	
	private List<T> originalDatas;
	
	public abstract void convert(AdapterViewHolder holder, T data);
	
	public abstract boolean getFilterCondition(T data, String keyword);

	public AbsFilterableAdapter(Context context, List<T> datas, int layoutId) {
		this.context = context;
		inflater = LayoutInflater.from(context);
		this.datas = datas;
		this.layoutId = layoutId;
	}

	@Override
	public int getCount() {
		return datas.size();
	}

	@Override
	public T getItem(int position) {
		return datas.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		AdapterViewHolder holder = AdapterViewHolder.getInstance(context, convertView, parent, layoutId, position);
		convert(holder, getItem(position));
		return holder.getConvertView();
	}

	@Override
	public Filter getFilter() {
		return new Filter() {
			
			@SuppressWarnings("unchecked")
			@Override
			protected void publishResults(CharSequence constraint, FilterResults results) {
				datas = (List<T>) results.values;
                notifyDataSetChanged();
			}
			
			@Override
			protected FilterResults performFiltering(CharSequence constraint) {
				FilterResults results = new FilterResults();
                List<T> FilteredArrList = new ArrayList<T>();

                if (originalDatas == null) {
                	originalDatas = new ArrayList<T>(datas);
                }

                if (TextUtils.isEmpty(constraint)) {
                    results.count = originalDatas.size();
                    results.values = originalDatas;
                } else {
                    String keyword = constraint.toString().trim();
                    for (T data: originalDatas) {
                        if (getFilterCondition(data, keyword)) {
                            FilteredArrList.add(data);
                        }
                    }
                    results.count = FilteredArrList.size();
                    results.values = FilteredArrList;
                }
                return results;
			}
		};
	}

}
